package com.learn.yh.aws;

import com.zaxxer.hikari.util.DriverDataSource;
import org.apache.commons.lang3.RandomUtils;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * @author: Yh
 * @date: 2021/4/15 15:51
 */
public class IDriverDataSource implements DataSource {
    private final DriverDataSource source;

    public IDriverDataSource(DriverDataSource source) {
        this.source = source;
    }

    @Override
    public Connection getConnection() throws SQLException {
        try {
            resetUserNameAndPassword();
            return source.getConnection();
        } catch (SQLException e) {
            System.out.println(e.getSQLState());
        }
        return null;
    }

    private void resetUserNameAndPassword() {
        try {
            Field driverProperties = source.getClass().getDeclaredField("driverProperties");
            Properties o = (Properties) driverProperties.get(source);
            driverProperties.setAccessible(true);
            boolean b = RandomUtils.nextBoolean();
            System.out.println(b);
            if (b) {
                o.put("user", "root");
            } else {
                o.put("user", "ro0t");
            }
        } catch (IllegalAccessException | NoSuchFieldException illegalAccessException) {
            illegalAccessException.printStackTrace();
        }
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return source.getConnection(username, password);
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return source.getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter logWriter) throws SQLException {
        source.setLogWriter(logWriter);
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return source.getLoginTimeout();
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        source.setLoginTimeout(seconds);
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return source.getParentLogger();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return source.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return source.isWrapperFor(iface);
    }
}
